package com.hexorld.main;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.hexorld.core.GameBoardView;

public class GameView extends SurfaceView implements SurfaceHolder.Callback{

	private GameBoardView mGameBoardView = null;
	private SurfaceHolder mHolder;
	private Context mContext = null;
	private boolean mRun = true;
	private int mMode = STATE_RUNNING;

    public static final int STATE_LOSE = 1;
    public static final int STATE_PAUSE = 2;
    public static final int STATE_READY = 3;
    public static final int STATE_RUNNING = 4;
    public static final int STATE_WIN = 5;
    
	public GameView(Context context) {
		super(context);
		mContext = context;
		initView();
	}
	
	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initView();
	}
	
	private void initView(){
		mGameBoardView = new GameBoardView(mContext);
		mHolder = this.getHolder();
		mHolder.addCallback(this);
		setFocusable(true);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		new Thread(new BoardThread()).start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}

	class BoardThread implements Runnable{

		@Override
		public void run() {
			while(mRun)
			{
                Canvas canvas = null;
                try {
                	canvas = mHolder.lockCanvas(null);
                    synchronized (mHolder) {
                        if (mMode == STATE_RUNNING) 
                        	mGameBoardView.update();
                        mGameBoardView.draw(canvas);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (canvas != null) {
                    	mHolder.unlockCanvasAndPost(canvas);
                    }
                }

				try{
					Thread.sleep(100);
				}catch(Exception e)
				{
					
				}
			}
		}
		
	}

	
	
}
